<template>
  <div class="table-container">
    <el-table
      v-loading="listLoading"
      v-on:sort-change="sortHandler"
      :data="tableData"
      style="width: 100%"
      :default-sort = "{ prop: 'created_at', order: 'descending'} "
      highlight-current-row>
      <el-table-column
        prop="tel"
        :label="$t('user.tel')">
      </el-table-column>
      <el-table-column
        prop="name"
        sortable
        :label="$t('login.userName')">
      </el-table-column>
      <el-table-column
        prop="login_ip"
        :label="$t('user.loginIp')">
      </el-table-column>
      <el-table-column
        prop="status"
        :label="$t('user.isBan')">
        <template slot-scope="scope">
          {{ scope.row.status === 0 ? $t('no') : $t('yes') }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('user.isSupper')">
        <template slot-scope="scope">
          {{ scope.row.supper === 0 ? $t('no') : $t('yes') }}
        </template>
      </el-table-column>
      <el-table-column
        prop="created_at"
        sortable
        :label="$t('user.createdAt')">
        <template slot-scope="scope">
          {{ scope.row.created_at }}
        </template>
      </el-table-column>
      <el-table-column
        prop="updated_at"
        sortable
        :label="$t('user.updatedAt')">
        <template slot-scope="scope">
          {{ scope.row.updated_at }}
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        :label="$t('user.role')">
        <template slot-scope="scope">
          {{ getDisplayRole(scope.row.roles) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('operation')">
        <template slot-scope="scope">
          <el-button @click="checkUser(scope.row)" type="text" size="small">{{$t('check')}}</el-button>
          <el-button @click="editUser(scope.row)" type="text" size="small">{{$t('edit')}}</el-button>
          <el-button v-if="scope.row.is_del === 1" @click="deleteConfirm(scope.row)" type="text" size="small">{{$t('remove')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-container">
      <el-pagination v-show="total>0" :current-page="listQuery.page" :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" :total="total" background layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    </div>
  </div>
</template>

<script>
export default {
  name: "UserTable",
  props: {
    tableData: {
      type: Array,
      required: true
    },
    // tableData's total count
    total: {
      type: Number,
      required: true
    },
    listLoading: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      // data query condition
      listQuery: {
        page: 1,
        limit: 10
      }
    };
  },
  methods: {
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.emitSearchEvent()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.emitSearchEvent()
    },
    sortHandler(val) {
      const { prop, order } = val
      this.$emit("update:search", {
        sort: {
          prop,
          order
        }
      })
    },
    emitSearchEvent() {
      this.$emit("update:search", {
        ...this.listQuery
      })
    },
    deleteConfirm(row) {
      this.$confirm(this.$t('user.removeUserConfirmContent'), this.$t('user.removeUserConfirmTitle'), {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // this.deleteUserById([row.admin_id])
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })       
        })
    },
    /**
     * 根据id删除用户
     */
    deleteUserById(ids) {
      this.$store.dispatch('deleteUserByIDs', { admin_ids: ids })
        .then(data => {
          if (data && data['code'] === 0) {
            this.$notify({
              title: this.$t('operationSuccess'),
              message: data['msg'],
              type: 'success'
            })
          } else {
            this.$notify({
              title: this.$t('operationFailed'),
              message: data['msg'],
              type: 'warning'
            })
          }

          // 发射search事件，刷新列表
          this.emitSearchEvent()
        }).catch(error => {
          console.error('delete user by ids has error:', error)
          this.$notify.error({
            title: this.$t('operationFailed'),
            message: this.$t('errorTips'),
          })
        })
    },
    checkUser(row) {
      this.$router.push({path:'/user/detail', query:{userID: row.admin_id}})
    },
    editUser(row) {
      this.$router.push({path:'/user/editUser', query:{userID: row.admin_id}})
    },
    getDisplayRole(roles) {
      let result = ''
      if (Array.isArray(roles)) {
        result = roles.map(item => {
          return item.name
        })
        result = result.toString()
      }
      return result
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.table-container {
  .page-container {
    padding-top: 15px;
  }
}
</style>

